import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'services/app_state_service.dart';
import 'services/storage_service.dart';
import 'pages/login_page.dart';
import 'pages/home_page.dart';

/// 应用程序入口点
/// 启动Flutter应用程序
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化存储服务
  await StorageService.init();
  
  runApp(const QxxzsApp());
}

/// 应用程序根组件
/// 配置全局主题和路由
class QxxzsApp extends StatelessWidget {
  const QxxzsApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => AppStateService()),
      ],
      child: ScreenUtilInit(
        designSize: const Size(375, 812), // 设计稿尺寸
        minTextAdapt: true,
        splitScreenMode: true,
        builder: (context, child) {
          return MaterialApp(
            title: 'QXXZS Flutter App',
            debugShowCheckedModeBanner: false, // 隐藏调试横幅
            theme: ThemeData(
              // 使用Material 3设计语言
              useMaterial3: true,
              // 定义应用主题色彩
              colorScheme: ColorScheme.fromSeed(
                seedColor: Colors.blue,
                brightness: Brightness.light,
              ),
              // 应用栏主题
              appBarTheme: const AppBarTheme(
                centerTitle: true,
                elevation: 2,
              ),
            ),
            home: const AppInitializer(),
          );
        },
      ),
    );
  }
}

/// 应用初始化组件
/// 负责检查登录状态并决定显示哪个页面
class AppInitializer extends StatefulWidget {
  const AppInitializer({super.key});

  @override
  State<AppInitializer> createState() => _AppInitializerState();
}

class _AppInitializerState extends State<AppInitializer> {
  bool _isInitializing = true;

  @override
  void initState() {
    super.initState();
    _initializeApp();
  }

  Future<void> _initializeApp() async {
    try {
      // 初始化应用状态
      await context.read<AppStateService>().init();
    } catch (e) {
      debugPrint('应用初始化失败: $e');
    } finally {
      setState(() {
        _isInitializing = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isInitializing) {
      return const Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    // 根据登录状态决定显示哪个页面
    final isLoggedIn = context.watch<AppStateService>().isLoggedIn;
    
    return isLoggedIn ? const HomePage() : const LoginPage();
  }
}

